﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using DDTek.Oracle;
using System.Data;
using QueryZJK.Helpers;
using System.Diagnostics;

namespace QueryZJK.Common
{
    public class OracleHelper : IDao
    {
        protected OracleHelper()
        {
        }

        static OracleHelper instance = null;
        public static OracleHelper Instance
        {
            get
            {
                return instance ?? (instance = new OracleHelper());
            }
        }


        public DataTable Select(string sql)
        {
            OracleConnection conn = GetConnection();

            DataTable data = new DataTable();
            try
            {
                SelectImplement(conn, sql, data);
            }
            catch (Exception ee)
            {
                throw new InvalidExpressionException(ee.Message + ":" + sql, ee);
            }
            finally
            {
                conn.Close(); //关闭连接
            }

            return data;
        }

        void SelectImplement(OracleConnection conn, string sql, DataTable data)
        {
            conn.Open();
            OracleCommand cmd = conn.CreateCommand();
            cmd.CommandText = sql;

            var reader = cmd.ExecuteReader();
            var fieldCount = reader.FieldCount;

            //添加每列的列头
            for (int i = 0; i < fieldCount; i++)
            {
                DataColumn column = new DataColumn(reader.GetName(i));
                data.Columns.Add(column);
            }

            //每次循环就是一条记录
            while (reader.Read())
            {
                DataRow row = data.NewRow();
                for (int i = 0; i < fieldCount; i++)
                {
                    row[reader.GetName(i)] = reader[i];
                }
                data.Rows.Add(row);
            }
        }

        public bool IsConnected()
        {
            
            OracleConnection conn = GetConnection();
            //string sql = "SELECT sysdate FROM dual";



            bool tof = true;
            try
            {
                conn.Open();
                //OracleCommand cmd = conn.CreateCommand();
                //cmd.CommandText = sql;
                //object result = cmd.ExecuteScalar();
            }
            catch (Exception e)
            {
                tof = false;
                throw e;
            }

            return tof;

        }


        OracleConnection GetConnection()
        {           
            return new OracleConnection(ConfigHelper.DbConnectStr);
        }
    }
}
